//
//  HMComposeView.swift
//  Weibo
//
//  Created by teacher on 2017/6/11.
//  Copyright © 2017年 teacher. All rights reserved.
//

import UIKit
import pop

//  撰写视图罩层
class HMComposeView: UIView {

    //  记录6个菜单按钮数组
    fileprivate lazy var composeButtonArray: [HMComposeButton] = [HMComposeButton]()
    //  菜单模型数组
    fileprivate lazy var composeModelArray: [HMCompose] = {
        let modelArray = self.readComposeData()
        return modelArray
    }()
    
    //  MARK:   -懒加载控件
    fileprivate lazy var bgImageView: UIImageView = {
        //  图片模糊化处理
        let image = self.getScreenShot().applyLightEffect()
        let imageView = UIImageView(image: image)
        return imageView
    }()
    
    //  记录目标控制器
    var target: UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = RandomColor()
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        
        addSubview(bgImageView)
        addChildButton()
        
    }
    
    //  添加按钮
    private func addChildButton() {
        //  按钮的宽度
        let buttonWidth: CGFloat = 80
        //  按钮的高度
        let buttonHeight: CGFloat = 110
        //  按钮的间距
        let buttonMargin: CGFloat = (width - 3 * buttonWidth) / 4
        
        for i in 0..<composeModelArray.count {
            let button = HMComposeButton()
            button.tag = i
            //  计算列索引
            let colIndex = i % 3
            //  计算行索引
            let rowIndex = i / 3
            //  计算x坐标
            let x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            //  计算x坐标
            let y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            //  设置frame
            button.frame = CGRect(x: x, y: y, width: buttonWidth, height: buttonHeight)
            //  添加点击事件
            button.addTarget(self, action: #selector(composeButtonAction(btn:)), for: .touchUpInside)
            //  获取菜单对应的模型
            let model = composeModelArray[i]
            button.setImage(UIImage(named: model.icon!), for: .normal)
            button.setTitle(model.title!, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            button.setTitleColor(UIColor.darkGray, for: .normal)
            
            addSubview(button)
            //  记录按钮
            composeButtonArray.append(button)
        }
    }
    
    //  MARK:   --撰写按钮点击事件处理
    @objc private func composeButtonAction(btn: HMComposeButton) {
        
        UIView.animate(withDuration: 0.25, animations: { 
            
            for button in self.composeButtonArray {
                //  设置透明度
                button.alpha = 0.3
                if button == btn {
                    //  放大
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    //  缩小
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }

        }) { (_) in
            UIView.animate(withDuration: 0.25, animations: { 
                for button in self.composeButtonArray {
                    //  设置透明度
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                //  动画执行完成回调
                //  根据撰写视图控制器的类创建实例
                
                /*
                    字符串转成实例对象
                        1. 自定义的类名需要加上命名空间
                        2. 类型需要转成成指定类型
                        3. 使用类型创建实例的时候，不能使用‘()’, 需要使用‘类型.init()’
                 */
                //  获取按钮对应的模型
                let model = self.composeModelArray[btn.tag]
                //  1.通过字符串获取对应的类型
                let classType = NSClassFromString(model.className!) as! UIViewController.Type
                //  2.根据类型创建实例
                let vc = classType.init()
                //  创建导航视图控制器
                let nav = HMNavigationController(rootViewController: vc)
               
                //  需要视图控制器
                self.target?.present(nav, animated: true, completion: { 
                    self.removeFromSuperview()
                })
            })
        }
    }
    
    //  开启pop动画
    private func startPopAnimation(isUp: Bool) {
        
        if isUp == false {
            //  向下pop动画
            composeButtonArray = composeButtonArray.reversed()
        }
        
        for (i, button) in composeButtonArray.enumerated() {
            //  创建弹簧动画对象
            let popSpringAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isUp {
                //  动画执行目的地
                popSpringAnimation?.toValue = CGPoint(x: button.center.x, y: button.center.y - 350)
            } else {
                //  动画执行目的地
                popSpringAnimation?.toValue = CGPoint(x: button.center.x, y: button.center.y + 350)
            }
            
            //  设置幅度
            popSpringAnimation?.springBounciness = 10
            //  设置弹簧初始化速度
            popSpringAnimation?.springSpeed = 10
            //  设置动画间隔时间
            popSpringAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            
            //  执行pop动画
            button.pop_add(popSpringAnimation, forKey: nil)
        }
        
    }
    
    //  截取window图片
    private func getScreenShot() -> UIImage {
        
        let window = UIApplication.shared.keyWindow!
        //  开启图片上下午
        UIGraphicsBeginImageContext(window.size)
        
        //  根据指定区域截取图片
        //  afterScreenUpdates: 表示是否需要等到屏幕更新后再截取
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: false)
        //  从图片上下文中获取截图的图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //  关闭图片上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    //  读取plist文件数据
    private func readComposeData() -> [HMCompose] {
        //  plist文件路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        //  读取plist数据
        let dicArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        //  使用YYModel完成字典转模型
        let modelArray = NSArray.yy_modelArray(with: HMCompose.self, json: dicArray) as! [HMCompose]
        return modelArray
    }
    
    //  显示罩层视图
    func show(target: UIViewController) {
        self.target = target
    
        //  获取window
//        let window = UIApplication.shared.keyWindow
//        //  添加子视图
//        window?.addSubview(self)
        //  如果添加到window上会挡住视图控制器
        self.target?.view.addSubview(self)
        //  开启pop动画
        startPopAnimation(isUp: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        startPopAnimation(isUp: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { 
            self.removeFromSuperview()
        }
    }
   
}
